<template>
  <div class="content">
    <div class="ui-container">
      <BasicForm @submit="menuSelect" @register="registerForm" />
      <div class="nav">
        <div class="check-row min-w-[120px]">
          <a-checkbox
            v-model:checked="state.checkAll"
            :indeterminate="state.indeterminate"
            @change="onCheckAllChange"
            class="mt-[100px]"
          >
            <span class="text-[12px] text-cool-[#717a92]">
              选中【<span>{{ state.checkedList.length }}</span
              >】条</span
            >
          </a-checkbox>
        </div>
        <div class="bg-cool-[#fcfcfc]">
          <a-menu v-model:selectedKeys="currentType" mode="horizontal" @select="menuSelect">
            <a-menu-item key="all">
              <template #icon>
                <unordered-list-outlined />
              </template>
              全部
            </a-menu-item>
            <a-menu-item key="ques">
              <template #icon>
                <user-outlined />
              </template>
              我提出的问题
            </a-menu-item>
            <a-menu-item key="manager">
              <template #icon>
                <team-outlined />
              </template>
              我负责的问题
            </a-menu-item>
            <a-menu-item key="execute">
              <template #icon>
                <thunderbolt-outlined />
              </template>
              进行中
            </a-menu-item>
            <a-menu-item key="over">
              <template #icon>
                <minus-outlined />
              </template>
              已完成
            </a-menu-item>
            <a-menu-item key="close">
              <template #icon>
                <appstore-outlined />
              </template>
              已关闭
            </a-menu-item>
          </a-menu>
        </div>
        <div class="steptool">
          <a-button type="primary" @click="go({ path: '/quesLib/form' })">
            <Icon icon="ant-design:question-outlined" /> 提出问题
          </a-button>
          <a-button class="!bg-cool-[#ff7661]" @click="quesOpe(3)">
            <Icon icon="ant-design:close-circle-filled" /> 关闭问题
          </a-button>
          <a-button class="!bg-cool-[#ffc400]" @click="quesOpe(2)">
            <Icon icon="ant-design:check-circle-filled" /> 打开问题
          </a-button>
          <a-button type="primary" @click="go({ path: '/quesLib/help' })">
            <Icon icon="ant-design:question-outlined" /> 帮助文档
          </a-button>
        </div>
      </div>
      <a-checkbox-group v-model:value="state.checkedList" class="w-[100%] mb-28">
        <a-spin :spinning="loading">
          <a-list item-layout="horizontal" :data-source="data" class="pb-[60px]">
            <template #renderItem="{ item, index }">
              <ListItem :item="item" :index="index" :checkedList="state.checkedList" />
            </template>
          </a-list>
        </a-spin>
      </a-checkbox-group>
      <div class="footer">
        <a-pagination
          v-model:current="currentpage"
          v-model:total="total"
          :responsive="true"
          :defaultPageSize="20"
          :hideOnSinglePage="true"
          @change="change"
        />
      </div>
    </div>
  </div>
</template>
<script lang="ts">
  export default defineComponent({
    name: 'ViewsQuesLibIndex',
  });
</script>
<script lang="ts" setup>
  import { Icon } from '/@/components/Icon';
  import { defineComponent, onMounted, ref, watch, reactive } from 'vue';
  import { BasicForm, useForm, FormSchema } from '/@/components/Form/index';
  import { formSet } from '/@/api/test/testData';
  import { formSchemas } from '/@/utils/custom';
  import { router } from '/@/router';
  import {
    QueslibInfo,
    queslibInfoListData,
    queslibInfoUpdateStep,
  } from '/@/api/quesLib/info/queslibInfo';
  import {
    UnorderedListOutlined,
    AppstoreOutlined,
    UserOutlined,
    TeamOutlined,
    ThunderboltOutlined,
    MinusOutlined,
  } from '@ant-design/icons-vue';
  import { useUserStore } from '/@/store/modules/user';
  import { useGo } from '/@/hooks/web/usePage';
  import { unref } from 'vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useDict } from '/@/components/Dict/src/useDict';
  import ListItem from './list/listItem.vue';
  const { initDict } = useDict();
  const userStore = useUserStore();

  const { showMessage } = useMessage();
  const go = useGo();
  const [registerForm, { resetFields, setProps, getFieldsValue }] = useForm();

  let formConfig = ref<any>({});
  let inputFormSchemas: FormSchema[] = [];

  const currentType = ref<string[]>(['all']);
  let data = ref<QueslibInfo[]>([]);
  const currentpage = ref(1);
  const total = ref(0);
  const pageSize = ref(20);
  const loading = ref(false);

  const state = reactive({
    indeterminate: true,
    checkAll: false,
    checkedList: [],
  });

  watch(
    () => unref(state.checkedList),
    (val) => {
      state.indeterminate = !!val.length && val.length < data.value.length;
      state.checkAll = val.length === data.value.length;
    },
  );

  watch(
    () => router.currentRoute.value,
    (newValue) => {
      if (newValue.name === 'ViewsQuesLibIndex') {
        loadPage();
      }
    },
  );

  onMounted(async () => {
    await initDict(['quesLib_ques_step', 'quesLib_ques_type', 'quesLib_priority_level']);
    loadPage();
  });
  const loadPage = async () => {
    const configRes = await formSet({ viewCode: 'quesLib_search_form' });
    formConfig.value = configRes.layVoucherView.formConfig;
    inputFormSchemas = formSchemas(
      configRes.layVoucherView.formTabs[0].colList,
      formConfig.value.formColNum,
      {},
    ) as FormSchema[];
    setProps({
      labelWidth: 120, // 控件前面的标签宽度
      schemas: inputFormSchemas, // 控件定义列表
      baseColProps: { lg: parseInt(formConfig.value.formColNum), md: 24 },
      showActionButtonGroup: true,
      showAdvancedButton: true,
      submitButtonOptions: {
        text: '查询',
      },
      actionColOptions: {
        span: 5,
      },
      fieldMapToTime: [['dateRange', ['createDate_gte', 'createDate_let']]],
    });
    await resetFields(); // 重置表单数据
    await searchData();
  };

  async function searchData() {
    loading.value = true;
    try {
      let formData = getFieldsValue();
      let perams: any = {
        ...formData,
        pageNo: currentpage.value,
        pageSize: pageSize.value,
      };
      if (currentType.value['0'] == 'ques') {
        perams.createBy = userStore.getUserInfo.userCode;
      } else if (currentType.value['0'] == 'manager') {
        perams.manager = userStore.getUserInfo.userCode;
      } else if (currentType.value['0'] == 'over') {
        perams.milestone = '6';
      } else if (currentType.value['0'] == 'execute') {
        perams.step = '2';
      } else if (currentType.value['0'] == 'close') {
        perams.step = '3';
      }

      queslibInfoListData(perams).then((res) => {
        data.value = res.list;
        currentpage.value = res.pageNo;
        total.value = res.count;
        pageSize.value = res.pageSize;
        state.checkedList = [];
        loading.value = false;
      });
    } catch (error) {
      loading.value = false;
    }
  }

  const change = (page, size) => {
    console.log(page, size);
    pageSize.value = size;
    currentpage.value = page;
    searchData();
  };

  const menuSelect = () => {
    currentpage.value = 1;
    searchData();
  };

  const onCheckAllChange = (e: any) => {
    Object.assign(state, {
      checkedList: e.target.checked ? getAllIds() : [],
      indeterminate: false,
    });
  };

  const getAllIds = () => {
    const ids: string[] = [];
    data.value.forEach((item) => {
      ids.push(item.id);
    });
    return ids;
  };
  const quesOpe = async (ope) => {
    if (state.checkedList.length == 0) {
      showMessage('请选择一行数据！');
      return;
    }
    const perams = {
      selIds: state.checkedList.join(','),
      step: ope,
    };
    const res = await queslibInfoUpdateStep(perams);
    showMessage(res.message, 'success', 2);
    searchData();
  };
</script>
<style lang="less" scoped>
  .content {
    background-color: #ffffff;
    width: 100%;
    height: 100%;
  }
  .ui-container {
    width: 93%;
    //min-width: 800px;
    padding: 0 20px;
    margin: 0 auto;
    // overflow: scroll;
  }
  .nav {
    display: flex;
    background-color: #fcfcfc;
    height: 46px;
    div:nth-of-type(1) {
      flex-grow: 1;
      border-bottom: 1px solid #f0f0f0;
      line-height: 46px;
    }
    ul {
      background-color: #fcfcfc !important;
    }
    div:nth-of-type(2) {
      flex-grow: 3;
    }
    div:nth-of-type(3) {
      flex-grow: 1;
    }
    .check-row {
      width: 100px;
    }
  }
  .footer {
    position: fixed;
    width: 100%;
    bottom: 0px;
    background-color: #f0f2f5;
    height: 50px;
    left: 16px;
    z-index: 999;
    ul {
      text-align: center;
      margin-top: 10px;
      font-size: 16px;
    }
  }

  .steptool {
    right: 20px;
    bottom: 100px;
    z-index: 999;
    margin-top: -60px;
    position: fixed;
    display: -webkit-box;
    display: -ms-flexbox;
    display: flex;
    -webkit-box-orient: vertical;
    -webkit-box-direction: normal;
    -ms-flex-direction: column;
    flex-direction: column;
    -webkit-box-align: end;
    -ms-flex-align: end;
    align-items: flex-end;

    button {
      margin: 5px 0;
      border-radius: 12px;
      span {
        font-size: 16px;
        font-weight: bolder;
        font-family: 'Microsoft YaHei';
      }
    }
  }
</style>
